<template>
  <!-- 保存中药模板 -->
  <el-dialog title="存储中药模板" :visible="value" width="1000px" custom-class="dialog-box" @close="onClose" @open="onOpen" :close-on-click-modal="false" :append-to-body="true">
    <el-form @submit.native.prevent="onSubmit" label-position="top" ref="form" :model="form" :rules="rules">
      <el-form-item label="模板名称：" prop="traditionalMedicineDrugTemplate.name">
        <el-input v-model="form.traditionalMedicineDrugTemplate.name"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="模板分类：" prop="traditionalMedicineDrugTemplate.traditionalMedicineTemplateSortId">
            <el-cascader v-model="typeArrId" :show-all-levels="false" :options="typeArrayZY" :props="typeProps" clearable></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="模板类型：" prop="traditionalMedicineDrugTemplate.type">
            <el-radio-group v-model="form.traditionalMedicineDrugTemplate.type">
              <el-radio v-for="(item,index) in typeArr" :key="index" :label="item.id">{{item.desc}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <h4 style="margin:0;">医嘱内容：</h4>
      <br>
      <table class="table-box">
        <thead>
          <tr>
            <th>药品</th>
            <th>剂量</th>
            <th>单位</th>
            <th>说明</th>
            <th>总计</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item,index) in form.traditionalMedicineDrugTemplateMedicalAdviceItem" :key="index">
            <td> {{item.adviceName}}</td>
            <td>
              <el-form-item :prop="'traditionalMedicineDrugTemplateMedicalAdviceItem.' + index + '.timesDosage'" :rules="[rulesRequired,rulesNumber]">
                <el-input v-model.number="item.timesDosage" type="number" style="width:80px;"></el-input>
              </el-form-item>
            </td>
            <td>
              <el-form-item :prop="'traditionalMedicineDrugTemplateMedicalAdviceItem.' + index + '.timesUnit'" :rules="[rulesRequired]">
                <el-select style="width:100px;" v-model="item.timesUnit" placeholder="请选择">
                  <el-option v-for="(item,index) in oneDoseUnitArr" :key="index" :label="item.desc" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </td>
            <td>
              <el-form-item :prop="'traditionalMedicineDrugTemplateMedicalAdviceItem.' + index + '.desc'" :rules="[rulesRequired]">
                <el-input v-model="item.desc"></el-input>
              </el-form-item>
            </td>
            <td>{{item.useTotal}}{{item.timesUnit|changeAssist(oneDoseUnitArr)}}</td>
            <td>
              <el-link :underline="false" type="primary" @click="onDelItem(index)"><i class="el-icon-delete"></i></el-link>
            </td>
          </tr>
        </tbody>
      </table>
      <div v-if="form.traditionalMedicineDrugTemplateMedicalAdviceItem.length == 0" style="color:#999;padding:10px 0;text-align:center;">
        <i class="iconfont iconwushuju" style="font-size:40px;"></i>
        <div>暂无数据</div>
      </div>
      <br>
      <div>
        <dialogSearchDrug :patientId="patientId" :doctorId="doctorId" @addItem="addFormList" type="2"></dialogSearchDrug>
      </div>
      <br>
      <table width="100%" border="0" style="border-top:1px solid #eee;">
        <tr>
          <td>
            <el-form-item label="用法：" prop="traditionalMedicineDrugTemplateMedicalAdvice.usage" :rules="[rulesRequired]">
              <el-select v-model="form.traditionalMedicineDrugTemplateMedicalAdvice.usage" placeholder="请选择">
                <el-option v-for="(item,index) in useArr" :key="index" :label="item.desc" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </td>
          <td>

            <el-form-item label="频次：" prop="traditionalMedicineDrugTemplateMedicalAdvice.frequency" :rules="[rulesRequired,rulesNumber]">
              <el-select v-model="form.traditionalMedicineDrugTemplateMedicalAdvice.frequency" placeholder="请选择">
                <el-option v-for="(item,index) in frequencyArr" :key="index" :label="item.desc" :value="item.id"></el-option>
              </el-select>
            </el-form-item>

          </td>
          <td>
            <el-form-item label="天数：" prop="traditionalMedicineDrugTemplateMedicalAdvice.day" :rules="[rulesRequired,rulesNumber]">
              <el-input v-model.number="form.traditionalMedicineDrugTemplateMedicalAdvice.day" type="number"></el-input>
            </el-form-item>
          </td>
          <td>
            <el-form-item label="总副数：" prop="traditionalMedicineDrugTemplateMedicalAdvice.total" :rules="[rulesRequired,rulesNumber]">
              <el-input v-model.number="form.traditionalMedicineDrugTemplateMedicalAdvice.total" type="number"></el-input>
            </el-form-item>
          </td>

          <td>
            <el-form-item label="取药地点：" prop="traditionalMedicineDrugTemplateMedicalAdvice.takeMedicinePlace" :rules="[rulesRequired]">
              <el-select v-model="form.traditionalMedicineDrugTemplateMedicalAdvice.takeMedicinePlace" placeholder="请选择">
                <el-option v-for="(item,index) in getAddressArr" :key="index" :label="item.desc" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </td>
        </tr>
      </table>
      <el-button v-show="false" type="primary" native-type="submit" :loading="btnLoading"></el-button>
    </el-form>
    <span slot="footer">
      <el-button type="primary" :loading="btnLoading" @click="onSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import zyMixin from "../_js/zyMixin.js";
export default {
  mixins: [zyMixin],
  props: [
    "value",
    "doctorId",
    "deptId",
    "patientId",
    "defaultList",
    "curePrescriptionUse"
  ],
  components: {
    dialogSearchDrug: () => import("./dialogSearchDrug.vue")
  },
  data() {
    return {
      btnLoading: false,
      typeArrId: [],
      form: {
        traditionalMedicineDrugTemplate: {},
        traditionalMedicineDrugTemplateMedicalAdvice: {},
        traditionalMedicineDrugTemplateMedicalAdviceItem: []
      },
      rules: {
        "traditionalMedicineDrugTemplate.name": [
          { required: true, message: "此项必填", trigger: "blur" }
        ]
      },
      typeArr: [],
      //中药分类
      typeArrayZY: [],
      typeProps: {
        checkStrictly: true,
        value: "id",
        label: "name",
        children: "child"
      }
    };
  },
  created() {
    let th = this;
  },
  mounted() {
    let th = this;
    th.getCommonConfigByKey("模板类型").then(res => {
      th.typeArr = res;
    });
    th.form.traditionalMedicineDrugTemplate = {
      hpId: th.adminUser.hpId,
      name: "",
      id: "",
      type: 0,
      traditionalMedicineTemplateSortId: "",
      status: 0,
      refId: ""
    };
    th.form.traditionalMedicineDrugTemplateMedicalAdvice = {
      templateId: "",
      usage: "",
      frequency: "",
      day: "",
      total: "",
      takeMedicinePlace: "",
      id: "",
      createUserId: ""
    };
    th.getTypeZY();
  },
  methods: {
    //删除中药
    onDelItem(index) {
      let th = this;
      th.form.traditionalMedicineDrugTemplateMedicalAdviceItem.splice(index, 1);
    },
    //添加药品进列表
    addFormList(json) {
      let th = this;
      //判断是否重复添加
      let arrIndex = th.form.traditionalMedicineDrugTemplateMedicalAdviceItem.findIndex(
        d => {
          return d.medicalAdviceId == json.drugId;
        }
      );
      if (arrIndex > -1) return;
      let j = {
        timesDosage: json.oneDose,
        timesUnit: json.oneDoseUnit,
        total: "",
        id: "",
        templateMedicalAdviceId: "",
        medicalAdviceId: json.drugId,
        createUserId: "",
        desc: json.remark,
        adviceName: json.drugName
      };
      th.form.traditionalMedicineDrugTemplateMedicalAdviceItem.push(j);
    },
    //获取中药分类
    getTypeZY() {
      let th = this;
      th.$api.getTraditionalMedicineTemplateSortTree({}).then(res => {
        if (res.executed) {
          th.typeArrayZY = res.data;
        }
      });
    },
    onSubmit() {
      let th = this;
      let j = {};
      let fn = function() {
        th.btnLoading = true;
        th.$api
          .addTraditionalMedicineDrugTemplate(j)
          .then(res => {
            if (res.executed) {
              th.$message.success("操作完成");
              th.onClose();
            } else {
              th.$message.error(res.message);
            }
            th.btnLoading = false;
          })
          .catch(() => {
            th.btnLoading = false;
          });
      };
      th.$refs["form"].validate(v => {
        if (v) {
          if (th.typeArrId.length > 0) {
            th.form.traditionalMedicineDrugTemplate.traditionalMedicineTemplateSortId =
              th.typeArrId[th.typeArrId.length - 1];
          }
          //根据模板类型添加ID
          if (th.form.traditionalMedicineDrugTemplate.type == 0) {
            th.form.traditionalMedicineDrugTemplate.refId = th.deptId;
          } else {
            th.form.traditionalMedicineDrugTemplate.refId = th.doctorId;
          }
          j.traditionalMedicineDrugTemplate = JSON.stringify(
            th.form.traditionalMedicineDrugTemplate
          );
          j.traditionalMedicineDrugTemplateMedicalAdvice = JSON.stringify(
            th.form.traditionalMedicineDrugTemplateMedicalAdvice
          );
          j.traditionalMedicineDrugTemplateMedicalAdviceItem = JSON.stringify(
            th.form.traditionalMedicineDrugTemplateMedicalAdviceItem
          );
          fn();
        }
      });
    },
    // //计算药品总量（单个药品）
    // toCompute(obj) {
    //   let th = this;
    //   let value = 0;
    //   if (
    //     typeof th.form.curePrescriptionUse.day == "number" &&
    //     typeof obj.oneDose == "number" &&
    //     typeof th.form.curePrescriptionUse.dailyDose == "number"
    //   ) {
    //     let v =
    //       obj.oneDose *
    //       th.form.curePrescriptionUse.dailyDose *
    //       th.form.curePrescriptionUse.day;
    //     obj.useTotal = v;
    //     value = v;
    //   } else {
    //     obj.useTotal = 0;
    //   }
    // },
    // //计算总量(总)
    // calculateTheTotal() {
    //   let th = this;
    //   let day = th.form.curePrescriptionUse.day;
    //   let dailyDose = th.form.curePrescriptionUse.dailyDose;
    //   if (day && dailyDose) {
    //     th.form.curePrescriptionUse.totalDose =
    //       Number.parseInt(day) * Number.parseInt(dailyDose);
    //   }
    // },
    onOpen() {
      let th = this;
      th.$nextTick(function() {
        let defalutArr = [];
        th.defaultList.forEach(item => {
          let j = {
            timesDosage: item.oneDose,
            timesUnit: item.oneDoseUnit,
            total: "",
            id: "",
            templateMedicalAdviceId: "",
            medicalAdviceId: item.drugId,
            createUserId: th.adminUser.memberId,
            desc: item.remark,
            adviceName: item.drugName
          };
          defalutArr.push(j);
        });
        th.form.traditionalMedicineDrugTemplateMedicalAdviceItem = defalutArr;
        th.form.traditionalMedicineDrugTemplateMedicalAdvice = {
          templateId: "",
          usage: th.curePrescriptionUse.usage,
          frequency: th.curePrescriptionUse.frequency,
          day: th.curePrescriptionUse.day,
          total: th.curePrescriptionUse.totalDose,
          takeMedicinePlace: th.curePrescriptionUse.getAddress,
          id: "",
          createUserId: th.adminUser.memberId
        };
      });
    },
    onClose() {
      let th = this;
      th.$refs["form"].resetFields();
      th.typeArrId = [];
      th.form.traditionalMedicineDrugTemplateMedicalAdviceItem = [];
      th.$emit("input", false);
    }
  },
  watch: {

  }
};
</script>
<style lang="scss" scoped>
.table-box {
  td {
    .el-form-item {
      margin-bottom: 0 !important;
    }
  }
}
</style>
